// 功能是向服务器发送字符串并接收翻译结果
#include "../include/muduo/net/TcpClient.h"
#include "../include/muduo/net/EventLoopThread.h"
#include "../include/muduo/net/TcpConnection.h"
#include "../include/muduo/base/CountDownLatch.h"

#include <iostream>
#include <functional>

class TranslateClient
{
public:
    TranslateClient(const std::string& sip,int sport):_latch(1),
        _client(_loopthread.startLoop(),muduo::net::InetAddress(sip,sport),"TranslateClient")
    {
        // 与服务器连接建立 / 关闭时触发
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnection,this,std::placeholders::_1));
        // 收到服务器返回的数据时触发
        _client.setMessageCallback(std::bind(&TranslateClient::onMessage,this,
            std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }

    void connect()
    {
        _client.connect();
        _latch.wait();
    }

    bool send(const std::string& meg)
    {
        if(_conn->connected())
        {
            _conn->send(meg);
            return true;
        }
        return false;
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            _conn = conn;
            _latch.countDown();
        }
        else
        {
            _conn.reset();
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn,muduo::net::Buffer* buf,muduo::Timestamp timee)
    {
        std::cout<<"翻译结果:"<<buf->retrieveAllAsString()<<std::endl;
    } 
private:
    muduo::CountDownLatch _latch;// 保证同步关系
    muduo::net::EventLoopThread _loopthread; // 事件循环线程，内部包含一个EventLoop对象 负责处理客户端的网络事件
    muduo::net::TcpClient _client; // TCP 客户端对象，用于与服务器建立连接和收发数据
    muduo::net::TcpConnectionPtr _conn; // TCP 连接智能指针，保存与服务器的连接对象
};

int main()
{
    TranslateClient _client("127.0.0.1",8080);
    _client.connect();
    while(true)
    {
        std::string buf;
        std::cin>>buf;
        _client.send(buf);
    }
    return 0;
}